<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use think\facade\Log;
use think\facade\View;

class Index extends BaseController
{
    private $echostr;
    private $arr;
    public function index()
    {
        return View::fetch();
    }
    //公众号
    public function link()
    {
        $rt = $this->check($this->request);
        if ($rt){
            if (!empty($this->echostr)){
                ob_clean();//清除缓存
                echo $this->echostr;//返回给微信的字符串
            }else{
                $xml = file_get_contents("php://input");//接受xml包
                Log::record($xml);
                $this->arr = $this->xml2array($xml);
            }

        }
    }
    public function check($request)
    {
        $signature = $request->param("signature");
        $timestamp = $request->param("timestamp");
        $nonce = $request->param("nonce");
        $this->echostr = $request->param("echostr");
        $token = "fuziyue";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
//        Log::record($signature."|".$timestamp."|".$nonce);
//        Log::record($signature."|".$tmpStr);
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    //将微信的xml转换为数组
    protected function xml2array($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
}
